clc; clearvars; close all;
addpath('CEC2010\')
addpath('CEC2010\datafiles\');
addpath('CEC2010\javarandom\bin\');
addpath('CEC2010\javarandom\src\');
load 'datafiles/f04_opm.mat';
global initial_flag

NS = 50;   % 种群数
dim = 1000;   % 种群维度
s = 20;   % 子控件数目
upperBound = [100, 5, 32, 100, 5, 32, 100, 100, 100, 5, 32, 100, 100, 100, 5, 32, 100, 100, 100, 100];
lowerBound = [-100, -5, -32, -100, -5, -32, -100, -100, -100, -5, -32, -100, -100, -100, -5, -32, -100, -100, -100, -100];
bestYhistory = [];    % 保存每次迭代的最佳值


for funcNum = 4

    initial_flag = 0;    % 换一个函数initial_flag重置为0
    sampleX = lhsdesign(NS, dim).*(upperBound(funcNum) - lowerBound(funcNum)) + lowerBound(funcNum).*ones(NS, dim);    % 生成NS个种群,并获得其评估值
    sampleY = benchmark_func(sampleX, funcNum);
    [bestY, bestIndex] = min(sampleY);    % 获取全局最小值以及对应的种群
    lastBestY = bestY;
    bestX = sampleX(bestIndex, :);
    bestYhistory = [bestYhistory; bestY];
    deltaF = zeros(1, s);
    version = 2;
    evalue = 50;

    while evalue < 3 * 10 ^ 6     

        index = p;
        for i1 = 1 : s
            index1 = index(((i1 - 1) * (dim / s) + 1) : (i1 * (dim / s)));
            subX = sampleX(:, index1);
            subX = SaNSDE(subX, sampleY, bestX, index1, 50 * 5, dim / s, lowerBound(funcNum), upperBound(funcNum), @(x)benchmark_func(x, funcNum));
            sampleX(:, index1) = subX;
            sampleY = benchmark_func(sampleX, funcNum);   
            [bestY, bestIndex] = min(sampleY);    % 获取全局最小值以及对应的种群
            bestX = sampleX(bestIndex, :);
            deltaF(1, i1) = deltaF(1, i1) + lastBestY - bestY;
            lastBestY = bestY;
            evalue = evalue + 50 * (1 + (dim / s) * 5);
        end

        delta0 = 1;
        while delta0 == 1 || delta0 / lastBestY > 0.01
            [~, index2] = max(deltaF);
            index1 = index(((index2 - 1) * (dim / s) + 1) : (index2 * (dim / s)));
            subX = sampleX(:, index1);
            subX = SaNSDE(subX, sampleY, bestX, index1, 50 * 5, dim / s, lowerBound(funcNum), upperBound(funcNum), @(x)benchmark_func(x, funcNum));
            sampleX(:, index1) = subX;
            sampleY = benchmark_func(sampleX, funcNum);   
            [bestY, bestIndex] = min(sampleY);    % 获取全局最小值以及对应的种群
            bestX = sampleX(bestIndex, :);
            delta0 = lastBestY - bestY;
            deltaF(1, index2) = deltaF(1, index2) + delta0;
            lastBestY = bestY;
            if version == 1
                delta0 = 0;
            end
            evalue = evalue + 50 * (1 + (dim / s) * 5);
            disp(evalue);
        end
        bestYhistory = [bestYhistory; bestY];
        disp(evalue);
    end
end
plot(bestYhistory);
save('CCBCI.mat','bestYhistory');
legend('Y','Location', 'northeast');